package com.lyncs.ods.modules.wx.controller;

import com.lyncs.ods.config.WxMpConfiguration;
import com.lyncs.ods.modules.wx.entity.WxServiceMsgDto;
import com.lyncs.ods.modules.wx.enums.WxEeventType;
import com.lyncs.ods.modules.wx.enums.WxMessageType;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信回调统一入口
 *
 * @author alex
 * @date 2022-06-02 11:15
 */
@Slf4j
@RestController
@RequestMapping("/wx/{appId}")
@Api(tags = {"微信回调相关接口"})
public class WxCallbackController {

    @RequestMapping(value = "/check")
    public String checkWxToken(@PathVariable String appId,
                               @RequestParam(value = "signature", required = false) String signature,
                               @RequestParam(value = "timestamp", required = false) String timestamp,
                               @RequestParam(value = "echostr", required = false) String echostr,
                               @RequestBody(required = false) WxServiceMsgDto wxServiceMsgDto) {
        WxMpService wxMpService = WxMpConfiguration.getMpService(appId, WxMpServiceImpl.class);
        if (StringUtils.isNotEmpty(echostr)) {
            // 用于微信校验接口存在性，必须返回echostr
            return echostr;
        }

        // 只处理订阅与取消订阅消息
        if (null != wxServiceMsgDto && StringUtils.isNotEmpty(wxServiceMsgDto.getMsgType()) &&
                StringUtils.isNotEmpty(wxServiceMsgDto.getEvent())) {
            String msgType = wxServiceMsgDto.getMsgType();
            String event = wxServiceMsgDto.getEvent();
            boolean isSubcribe = WxMessageType.EVENT.getCode().equals(msgType) &&
                    (WxEeventType.SUBSCRIBE.getCode().equals(event)
                            || WxEeventType.UNSUBSCRIBE.getCode().equals(event));
            if (isSubcribe) {
                WxEeventType wxEeventType = WxEeventType.SUBSCRIBE.getCode().equals(event) ? WxEeventType.SUBSCRIBE : WxEeventType.UNSUBSCRIBE;
                //wxMpService.onFollowCallback(wxServiceMsgDto, wxEeventType);
            }
        }
        return null;
    }
}
